package com.dhcc.android.base.utils;

import android.app.PendingIntent;
import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.location.Location;
import android.net.ConnectivityManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Parcelable;
import android.preference.PreferenceManager;
import android.util.Log;

import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationListener;
import com.amap.api.location.LocationManagerProxy;
import com.amap.api.location.LocationProviderProxy;
import com.dhcc.android.base.base.MSApplication;

import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * @author pengling
 * @date 2014-1-19
 * @version 1.0
 * @desc 定位服务
 * 
 */
public class LocationService extends Service implements AMapLocationListener {

	private static final String TAG = "LocationSvc";
	private LocationManagerProxy locationManager;
	public static final String GPSLOCATION_BROADCAST_ACTION = "com.location.apis.gpslocationdemo.broadcast";
	private PendingIntent mPendingIntent;
	private SharedPreferences sp;
	@Override
	public IBinder onBind(Intent intent) {
		return null;
	}

	@Override
	public void onCreate() {
		sp = PreferenceManager.getDefaultSharedPreferences(this);
		locationManager = LocationManagerProxy.getInstance(this);
		// 取得网络配置历史记录
		String gpsRefreahTime = sp.getString(
				MSApplication.GPS_REFRESH_TIME, "5");
		String catchRange = sp.getString(MSApplication.CATCH_RANGE, "10");// 定位时间、精度？？？
		if(Constants.isNetworkAvailable(this)){
			locationManager.requestLocationData(
					LocationProviderProxy.AMapNetwork,
					Integer.parseInt(gpsRefreahTime) * 1000,
					Integer.parseInt(catchRange), this);
		}else{
			IntentFilter fliter = new IntentFilter(
					ConnectivityManager.CONNECTIVITY_ACTION);
			fliter.addAction(GPSLOCATION_BROADCAST_ACTION);
			registerReceiver(mGPSLocationReceiver, fliter);
			Intent intent = new Intent(GPSLOCATION_BROADCAST_ACTION);
			mPendingIntent = PendingIntent.getBroadcast(getApplicationContext(), 0,
					intent, 0);
			locationManager.requestLocationUpdates(
					LocationManagerProxy.GPS_PROVIDER, Integer.parseInt(gpsRefreahTime) * 1000, Integer.parseInt(catchRange),
					mPendingIntent);
			new Handler().postDelayed(new Runnable() {
                @Override
                public void run() {
                   if(!isGetGps){//没有获取GPS
                	   updateWithNewLocation(null);
                   }
                }
            }, 5000);
			
		}
	}
	boolean isGetGps=false;
	private BroadcastReceiver mGPSLocationReceiver = new BroadcastReceiver() {
		@Override
		public void onReceive(Context context, Intent intent) {
			// 接受广播
			if (intent.getAction().equals(GPSLOCATION_BROADCAST_ACTION)) {
				isGetGps=true;
				// 只进行一次定位，定位成功后移除定位请求
				locationManager.removeUpdates(mPendingIntent);
				Bundle bundle = intent.getExtras();
				// 获取bundle里的数据
				Parcelable parcelable = bundle
						.getParcelable(LocationManagerProxy.KEY_LOCATION_CHANGED);
				Location location = (Location) parcelable;
				if (location == null) {
					return;
				}
				updateWithNewLocation(location);
			}

		}
	};
	@Override
	public void onStart(Intent intent, int startId) {
	}

	@Override
	public boolean stopService(Intent name) {
		return super.stopService(name);
	}

	@Override
	public void onLocationChanged(Location location) {
		updateWithNewLocation(location);
	}

	@Override
	public void onProviderDisabled(String provider) {
	}

	@Override
	public void onProviderEnabled(String provider) {
	}

	@Override
	public void onStatusChanged(String provider, int status, Bundle extras) {
	}

	private void updateWithNewLocation(Location location) {
		SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		Log.d(TAG, "Get the current position \n" + location);
		String locationStr="没有获取到gps！",gps="0.000000,0.000000";
		if(location!=null){
			String dateString = formatter.format(location.getTime());
			DecimalFormat df= new DecimalFormat("######0.000000");//精确到小数点后的六位   
			gps=df.format(location.getLatitude())+","+df.format(location.getLongitude());
			locationStr=dateString+","+gps;
		}else{
			locationStr=locationStr+","+formatter.format(new Date());
		}
		// 通知Activity
		Intent intent = new Intent();
		intent.setAction(Constants.LOCATION_ACTION);
		intent.putExtra(Constants.LOCATION, locationStr);
		intent.putExtra(Constants.GPSFLAG, gps);
		Constants.GPS=gps;
		sendBroadcast(intent);

		// 如果只是需要定位一次，这里就移除监听，停掉服务。如果要进行实时定位，可以在退出应用或者其他时刻停掉定位服务。
		locationManager.removeUpdates(this);
		if(mPendingIntent!=null){
			locationManager.removeUpdates(mPendingIntent);
			unregisterReceiver(mGPSLocationReceiver);
		}
		locationManager.destory();
		stopSelf();
	}

	/* (non-Javadoc)
	 * @see com.amap.api.location.AMapLocationListener#onLocationChanged(com.amap.api.location.AMapLocation)
	 */
	@Override
	public void onLocationChanged(AMapLocation arg0) {
		updateWithNewLocation(arg0);
		
	}
}
